package com.zlq.myannotation;



import com.zlq.dao.LoginInfoDao;
import com.zlq.pojo.LoginInfo;
import com.zlq.utils.IpUtils;
import com.zlq.utils.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 系统日志：切面处理类
 */

@Component
@Aspect
@Slf4j
public class LoginLogAspect {

    @Autowired
    LoginInfoDao loginInfoDao;

    @Before(value = "execution(* com.zlq.service.UserService.login(..))")
    public void before() {
        System.out.println("before.........");
    }


    @AfterReturning(value = "execution(* com.zlq.service.UserService.login(..))")
    public void loginInfo(){

        HttpServletRequest request = ToolUtil.getRequest();
        String userName = String.valueOf(ToolUtil.getSession().getAttribute("username"));
        if (userName != null) {
                System.out.println("写入日志中......");
            }
            // 创建日志对象
            LoginInfo loginInfo = new LoginInfo();
            // 获取 IP 地址
            String addr = IpUtils.getIpAddress(request);

            //操作时间
            SimpleDateFormat sif = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


            loginInfo.setUsername(userName);
            loginInfo.setIp(addr);
            loginInfo.setLogintime(sif.format(new Date()));

        System.out.println(loginInfo.toString());

        System.out.println("执行在这里算是一半成功");

        loginInfoDao.insertLog(loginInfo);

        System.out.println("插入成功");

    }
    /**
     * 获取当前的request
     * 这里如果报空指针异常是因为单独使用spring获取request
     * 需要在配置文件里添加监听
     * <listener>
     * <listener-class>
     * org.springframework.web.context.request.RequestContextListener
     * </listener-class>
     * </listener>
     * @return
     */
    public HttpServletRequest getHttpServletRequest(){
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes)ra;
        HttpServletRequest request = sra.getRequest();
        return request;
    }

}




















